import request from '@/utils/request'
import OSS from 'ali-oss'
import dayjs from 'dayjs'
import { getSuffix, randomString, isExpirationForAliyunOssSts } from '@/utils/utils'
import { getOSSToken, setOSSToken } from '@/utils/auth'
import config from '@/config'

export async function getOssToken() {
  const sts = getOSSToken()
  if (isExpirationForAliyunOssSts(sts)) {
    const { data } = await request('/oss/token', {
      method: 'get',
    })
    setOSSToken(data)
    return data
  }
  return sts
}

export async function upload(file, folder, fileName) {
  const sts = await getOssToken()
  const client = new OSS({
    endpoint: config.endpoint,
    bucket: config.bucket,
    stsToken: sts.securityToken,
    accessKeyId: sts.accessKeyId,
    accessKeySecret: sts.accessKeySecret,
    secure: true,
  })
  const dayInstance = dayjs()
  fileName = fileName || randomString(24) + '.' + getSuffix(file.name)
  const objectKey = `${folder}/${dayInstance.year()}/${dayInstance.month() + 1}/${fileName}`
  return new Promise((resolve, reject) => {
    client.put(objectKey, file, {
      headers: {
        'Cache-Control': 'public,max-age=2592000',
      },
    }).then(() => {
      resolve({ url: "https://" + config.bucket + "." + config.endpoint + "/" + objectKey })
    }).catch(reject)
  })
}

export function uploadImage(file: File, fileName: string = "") {
  return upload(file, 'test/images', fileName)
}

export function uploadBiz(file, fileName) {
  return upload(file, 'biz', fileName)
}
